#include "svmClassify.h"
SVMClassify::SVMClassify(const char * _svmModelFile, const char * _recognitionFeatureFile, const char * _recognitionResultFile) 
{
  if( _svmModelFile == NULL )
    {
      ERROR("svmModelFile is NULL!") ;
      exit(-1) ;
    }
  if( _recognitionFeatureFile == NULL )
    {
      ERROR("recognition feature file is NULL!") ;
      exit(-1) ;
    }
  if( _recognitionResultFile == NULL )
    {
      ERROR("recognition result file is NULL!");
      exit(-1) ;
    }
  predict_label = 0.f ;
  model = NULL ;
  svmNodePtr = NULL ;
  loadSvmModel(_svmModelFile) ;
  classify(_recognitionFeatureFile,_recognitionResultFile) ;
  INFO1("**********recognition is finished*********") ;
}

SVMClassify::~SVMClassify() 
{
  if( model != NULL ) 
    svm_free_and_destroy_model(&model) ;
  if( svmNodePtr != NULL )
    delete [] svmNodePtr ;
}
void SVMClassify::loadSvmModel(const char * _svmModelFile) 
{
  model = svm_load_model(_svmModelFile) ;
}
bool SVMClassify::getClassify()
{
  INFO2("predict_label",predict_label) ;
  return (predict_label == 1.f) ;
}
void SVMClassify::classify(const char * _recognitiveFeatureFile, const char * _recognitionResultFile) 
{
  std::string buf ;
  std::ifstream fileInStream(_recognitiveFeatureFile) ;
  if( !fileInStream.is_open() ) 
    {
      ERROR("can't open the recognition feature file!") ;
      exit(-1) ;
    }
  int framesNum = 0 ;
  std::ofstream fileOutStream(_recognitionResultFile) ;
  int countsTab = 0 ;
  getline(fileInStream,buf);
  std::istringstream ss(buf) ;
  for( int i = 0 ; i < buf.size() ; ++ i )
    if( buf[i] == '\t' ) ++countsTab;
  ++ countsTab ;
  svmNodePtr = new svm_node[countsTab] ;
  int index = 0 ;
  while( ss >> svmNodePtr[index].value )
    {
      svmNodePtr[index].index = index ;
      ++index ;
    }
  svmNodePtr[index].value = -1 ;
  svmNodePtr[index].index = -1 ;

  if( index != countsTab - 1 ) 
    {
      INFO2("elems",index) ;
      INFO2("countsTab",countsTab) ;
      WARNING("features format is wrong!") ;
      return ;
    }
  int nr_class = svm_get_nr_class(model) ;

  double * prob_estimates = new double[nr_class] ;

  if( svm_check_probability_model(model) != 0 ) 
    INFO1("Model supports probability estimates") ;
  else
    INFO1("Model dost not support probability estimates") ;

  if( svm_check_probability_model(model) != 0 )
    {
      // 概率检测
      predict_label = svm_predict_probability(model,svmNodePtr,prob_estimates) ;
      fileOutStream << predict_label << "\t" ;
      for( int i = 0 ; i < nr_class ; ++ i )
	fileOutStream << prob_estimates[i] << "\t" ;
      std::cout << std::endl ;
    }
  else
    {
      // 分类检测
      predict_label = svm_predict(model,svmNodePtr) ;
      fileOutStream << predict_label << "\t" << std::endl ;
    }
  delete []prob_estimates ;
}

